package per.locke.xml.parser.book;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import per.locke.xml.pojo.Book;

import java.util.ArrayList;
import java.util.List;

public class BookSAXParserHandler extends DefaultHandler {

    private String value = null;

    private Book book = null;

    private List<Book> bookList = new ArrayList<Book>();

    private int i = 0;

    public List<Book> getBookList() {
        return bookList;
    }

    int bookIndex = 0;

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

        if (qName.equals("book")) {
            book = new Book();
            bookIndex++;

            int num = attributes.getLength();
            for (int i = 0; i < num; num++) {

                if (attributes.getQName(i).equals("id")) {
                    book.setId(attributes.getValue(i));
                }

            }
        }


    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
//        if (qName.equals("book")) {
//            bookList.add(book);
//            book = null;
//        } else if (qName.equals("name")) {
//            book.setName(value);
//        } else if (qName.equals("price")) {
//            book.setPrice(value);
//        } else if (qName.equals("author"))
//            book.setAuthor(value);
        switch (qName) {
            case "book":
                bookList.add(book);
                book = null;
                break;
            case "name":
                book.setName(value);
                break;
            case "author":
                book.setAuthor(value);
                break;
            case "price":
                book.setPrice(value);
                break;
            default:
                break;
        }

    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        value = new String(ch, start, length);
    }


}
